package com.wing.res.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.wing.common.enums.MaintenanceEnum;
import com.wing.common.enums.ProductEnum;
import com.wing.common.utils.UniqueIdGeneratorUtil;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.service.ProductDetailService;
import com.wing.res.dao.ResProTaskDao;
import com.wing.res.model.entity.*;
import com.wing.res.model.request.*;
import com.wing.res.model.response.ResProTaskDetailVo;
import com.wing.res.model.response.ResProTaskSearchVo;
import com.wing.res.service.*;
import com.wing.sell.model.entity.CustomerProductCatalog;
import com.wing.sell.model.entity.OrderProEnclosure;
import com.wing.sell.service.CustomerProductCatalogService;
import com.wing.sell.service.OrderProEnclosureService;
import com.wing.web.utils.JwtUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 研发任务-ServiceImpl
 *
 * @version 1.1.0
 * @Author hz
 * @Date 2024-09-19 15:33
 **/
@Service
public class ResProTaskServiceImpl extends ServiceImpl<ResProTaskDao, ResProTask> implements ResProTaskService {

    @Autowired
    private ProductDetailService productDetailService;

    @Autowired
    private CustomerProductCatalogService catalogService;

    @Autowired
    private OrderProEnclosureService orderProEnclosureService;

    @Autowired
    private ResProTaskService resProTaskService;

    @Autowired
    private ResProductDrawService resProductDrawService;

    @Autowired
    private ResProductMoldDrawService resProductMoldDrawService;

    @Autowired
    private ResProEchnologyParamService resProEchnologyParamService;

    @Autowired
    private ResProEchnologyParamVersionService resProEchnologyParamVersionService;

    @Autowired
    private ResProQualityProjectService resProQualityProjectService;

    @Autowired
    private ResProQualityVersionService resProQualityVersionService;

    @Autowired
    private BenchmarkBookService benchmarkBookService;

    @Autowired
    private ResProEchnologyParamVersionSkuService resProEchnologyParamVersionSkuService;

    /**
     * 分页查询任务列表
     *
     * @param pg
     * @param map
     * @return
     */
    @Override
    public Page<ResProTaskSearchVo> pageList4app(Page<ResProTaskSearchVo> pg, Map map, String noStatus) {
        List<ResProTaskSearchVo> vos = this.baseMapper.pageList4app(pg, map, noStatus);
        pg.setRecords(vos);
        return pg;
    }

    /**
     * 添加研发任务
     *
     * @param form
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int add(ResProTaskAddForm form) {
        // 1. 判断是否关联新的
        //判断code是否重复
        Long productId;
        String productCode;
        Long taskId = null;
        if (ProductEnum.ReviewUseOrNewEmum.CJXCP.getCode().equals(form.getIsUseOrAdd())) {
            ProductDetail productDetail = new ProductDetail();
            productDetail.setCreator(JwtUtils.getLoginUserId());
            productDetail.setCreatorName(JwtUtils.getLoginUsername());
            productDetail.setCreateTime(LocalDateTime.now());
            productDetail.setModifier(JwtUtils.getLoginUserId());
            productDetail.setModifierName(JwtUtils.getLoginUsername());
            productDetail.setUpdateTime(LocalDateTime.now());
            productDetail.setRemark(form.getInRemark());
            productDetail.setSellStatus("0");
            productDetail.setSkuCode(form.getInSkuCode());
            productDetail.setSkuName(form.getInSkuName());
            productDetail.setSkuSpec(form.getInSkuSpec());
            productDetail.setProductTypeId(form.getProductTypeId());
            productDetail.setProductNature(form.getProductNature());
            productDetail.setAssemblyNature(form.getAssemblyNature());
            productDetail.setBaseUnit(form.getInUnitId());
            productDetail.setMainCalWay(form.getMainCalWay());
            //主计量方式
            productDetail.setMainUnitId(form.getMainUnitId());
            //主计量单位
            productDetail.setMainUnitRate(form.getMainUnitRate());
            //主计量单位换算率
            productDetail.setSubCalWay(form.getSubCalWay());
            //辅计量方式
            productDetail.setSubUnitId(form.getSubUnitId());
            //辅计量单位
            productDetail.setSubUnitRate(form.getSubUnitRate());
            //辅计量单位换算率
            productDetail.setCostCheckType(form.getCostCheckType());
            //成本核算类型
            productDetail.setCheckStatus(form.getCheckStatus());
            //是否质检
            productDetail.setBoxStatus(form.getBoxStatus());
            //是否料箱管理
            productDetailService.save(productDetail);
            productId = productDetail.getId();
            productCode = form.getInSkuCode();
        } else {
            QueryWrapper<ProductDetail> productDetailQueryWrapper = new QueryWrapper<>();
            productDetailQueryWrapper.eq("sku_code",form.getInSkuCode());
            List<ProductDetail> productDetails = this.productDetailService.list(productDetailQueryWrapper);
            productId = productDetails.get(0).getId();
            ProductDetail byId = productDetailService.getById(productId);
            productCode = byId.getSkuCode();
        }
        // 来源客户订单
        if (form.getSource().equals(MaintenanceEnum.Task_Source_Enum.KHDD.getCode())) {
            //插入任务表
            ResProTask resProTask = ResProTask.builder()
                    .creator(JwtUtils.getLoginUserId())
                    .creatorName(JwtUtils.getLoginUsername())
                    .createTime(LocalDateTime.now())
                    .updateTime(LocalDateTime.now())
                    .modifier(JwtUtils.getLoginUserId())
                    .modifierName(JwtUtils.getLoginUsername())
                    .taskNo(UniqueIdGeneratorUtil.generateUniqueId("RW", "yyyyMMdd", 1000, 9999))
                    .cusProId(form.getOrderProId())
                    .skuId(productId)
                    .skuCode(productCode)
                    .cusProId(form.getCusSkuCode())
                    .customerId(form.getCustomerId())
                    .extProductId(form.getExtProductId())
                    .cusProUnitId(form.getCusProUnitId())
                    .planGivenTime(form.getPlanGivenTime())
                    .source(form.getSource())
                    .status(MaintenanceEnum.Task_Status_Enum.DQR.getCode())
                    .remark("手动添加客户订单研发任务!")
                    .isBom(ProductEnum.dictEmum.F.getCode())
                    .isCraftsmanship(ProductEnum.dictEmum.F.getCode())
                    .orderId(form.getCusProductOrder())
                    .build();
            resProTaskService.save(resProTask);
            taskId = resProTask.getId();

            OrderProEnclosure file = new OrderProEnclosure();
            file.setCreator(JwtUtils.getLoginUserId());
            file.setCreatorName(JwtUtils.getLoginUsername());
            file.setCreateTime(LocalDateTime.now());
            file.setModifier(JwtUtils.getLoginUserId());
            file.setModifierName(JwtUtils.getLoginUsername());
            file.setUpdateTime(LocalDateTime.now());
            file.setFileUrl(form.getAttachmentPdf());
            file.setFileName(form.getFileName());
            file.setOrderId(form.getCusProductOrder());
            file.setTechnologyRemark(form.getProcessDescription());
            file.setTaskId(taskId);
            orderProEnclosureService.save(file);
        }

        //自研产品
        else if (form.getSource().equals(MaintenanceEnum.Task_Source_Enum.ZYCP.getCode())) {
            //添加附件信息
            OrderProEnclosure file = new OrderProEnclosure();
            file.setCreator(JwtUtils.getLoginUserId());
            file.setCreatorName(JwtUtils.getLoginUsername());
            file.setCreateTime(LocalDateTime.now());
            file.setModifier(JwtUtils.getLoginUserId());
            file.setModifierName(JwtUtils.getLoginUsername());
            file.setUpdateTime(LocalDateTime.now());
            file.setFileUrl(form.getAttachmentPdf());
            file.setFileName(form.getFileName());
            file.setTechnologyRemark(form.getProcessDescription());
            orderProEnclosureService.save(file);

            //添加任务信息
            ResProTask resProTask = ResProTask.builder()
                    .creator(JwtUtils.getLoginUserId())
                    .creatorName(JwtUtils.getLoginUsername())
                    .createTime(LocalDateTime.now())
                    .updateTime(LocalDateTime.now())
                    .modifier(JwtUtils.getLoginUserId())
                    .modifierName(JwtUtils.getLoginUsername())
                    .taskNo(UniqueIdGeneratorUtil.generateUniqueId("RW", "yyyyMMdd", 1000, 9999))
                    .skuId(productId)
                    .skuCode(productCode)
                    .isBom("0")
                    .isCraftsmanship("0")
                    .customerId(form.getCustomerId())
                    .planGivenTime(form.getPlanGivenTime())
                    .source(form.getSource())
                    .status(MaintenanceEnum.Task_Status_Enum.DQR.getCode())
                    .remark("手动添加自研任务!")
                    .orderId(form.getCusProductOrder())
                    .zyEnclosureId(file.getId())
                    .build();
            resProTaskService.save(resProTask);
            taskId = resProTask.getId();
        }

        LocalDate currentDate = LocalDate.now();
        // 获取当前年份
        int currentYear = currentDate.getYear();
        //插入图纸表
        ResProductDraw draw = ResProductDraw.builder().creator(JwtUtils.getLoginUserId()).creatorName(JwtUtils.getLoginUsername())
                .createTime(LocalDateTime.now()).updateTime(LocalDateTime.now()).modifier(JwtUtils.getLoginUserId())
                .modifierName(JwtUtils.getLoginUsername()).versionName(UniqueIdGeneratorUtil.generateUniqueId("", "yyyyMMdd", 1000, 9999))
                .isDefault("1")
                .productDetailId(productId)
                .remark(form.getProcessDescription())
                .versionName("ves."+currentYear+"-"+1)
                .isRelevance("0")
                .taskId(taskId)
                .build();
        resProductDrawService.save(draw);

        //添加检测项
        ResProQualityAddForm resProProcessAddForm = new ResProQualityAddForm();
        resProProcessAddForm.setSkuCode(productCode);
        resProProcessAddForm.setProductDetailId(productId);
        resProProcessAddForm.setTestItemData(form.getTestItemData());
        this.addSkuQuality(resProProcessAddForm);
        return 1;
    }

    /**
     * 查看任务详情
     *
     * @param id
     * @return
     */
    @Override
    public ResProTaskDetailVo resProTaskDetail(String id) {
        ResProTaskDetailVo detailVo = this.baseMapper.getOneProTaskBy(id);
        //如果是自研的话 附件信息查法就不同
        if (ObjectUtil.isNotEmpty(detailVo)) {
            if (detailVo.getSource().equals(MaintenanceEnum.Task_Source_Enum.ZYCP.getCode())) {
                OrderProEnclosure enclosure = orderProEnclosureService.getById(detailVo.getZyEnclosureId());
                if (ObjectUtil.isNotEmpty(enclosure)) {
                    detailVo.setCusProductFigure(enclosure.getFileName());
                    detailVo.setAttachmentPdfUrl(enclosure.getFileUrl());
                    detailVo.setProcessDescription(enclosure.getTechnologyRemark());
                }
            } else {
                QueryWrapper<OrderProEnclosure> enclosureQueryWrapper = new QueryWrapper<>();
                enclosureQueryWrapper.eq("task_id",id);
                OrderProEnclosure one = orderProEnclosureService.getOne(enclosureQueryWrapper);
                if (ObjectUtil.isNotEmpty(one)){
                    detailVo.setAttachmentPdfUrl(one.getFileUrl());
                    detailVo.setCusProductFigure(one.getFileName());
                    //工艺说明
                    detailVo.setProcessDescription(one.getTechnologyRemark());
                }
            }
        }
        return detailVo;
    }

    @Override
    public  List<ResProTaskDetailVo> getProTaskDetailBySkuCode(String skuCode) {
        List<ResProTaskDetailVo> detailVos = this.baseMapper.getProTaskDetailBySkuCode(skuCode);
        if (CollectionUtil.isNotEmpty(detailVos)) {
            ResProTaskDetailVo detailVo = detailVos.get(0);
            //如果是自研的话 附件信息查法就不同
            if (detailVo.getSource().equals(MaintenanceEnum.Task_Source_Enum.ZYCP.getCode())) {
                OrderProEnclosure enclosure = orderProEnclosureService.getById(detailVo.getZyEnclosureId());
                if (ObjectUtil.isNotEmpty(enclosure)) {
                    detailVo.setCusProductFigure(enclosure.getFileName());
                    detailVo.setAttachmentPdfUrl(enclosure.getFileUrl());
                }
            }
        }
        return detailVos;
    }

    /**
     * 添加sku产品工序
     *
     * @param resProProcessAddForm
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addSkuProcess(ResProProcessAddForm resProProcessAddForm) {

        //拿到原来的产品图纸
//        ResProductDraw byId = resProductDrawService.getById(resProProcessAddForm.getTzId());
//        byId.setIsRelevance(resProProcessAddForm.getIsRelevance());
//        byId.setUpdateTime(LocalDateTime.now());
//        byId.setModifier(JwtUtils.getLoginUserId());
//        byId.setModifierName(JwtUtils.getLoginUsername());
//        resProductDrawService.updateById(byId);

        // 1. 判断有没有关联图纸
//        if ("1".equals(resProProcessAddForm.getIsRelevance())) {
//            //有上传模具图纸就需要更新模具图纸
//            QueryWrapper<ResProductMoldDraw> wrapper = new QueryWrapper<>();
//            wrapper.eq("draw_id", resProProcessAddForm.getTzId());
//            wrapper.eq("is_default",1);
//            //查询图纸信息
//            ResProductMoldDraw one = resProductMoldDrawService.getOne(wrapper);
//
//            //新增
//            if (ObjectUtil.isEmpty(one)) {
//                ResProductMoldDraw moldDraw = ResProductMoldDraw.builder()
//                        .creator(JwtUtils.getLoginUserId())
//                        .creatorName(JwtUtils.getLoginUsername())
//                        .createTime(LocalDateTime.now())
//                        .updateTime(LocalDateTime.now())
//                        .modifier(JwtUtils.getLoginUserId())
//                        .modifierName(JwtUtils.getLoginUsername())
//                        .name(resProProcessAddForm.getMoldName())
//                        .code(UniqueIdGeneratorUtil.generateUniqueId("MD", "yyyyMMdd", 1000, 9999))
//                        .skuCode(byId.getSkuCode())
//                        .productDetailId(byId.getProductDetailId())
//                        .drawId(resProProcessAddForm.getTzId())
//                        //模具版本
//                        .versionName(UniqueIdGeneratorUtil.generateUniqueId("", "yyyyMMdd", 1000, 9999))
//                        .isDefault("1")
//                        .fileUrl(resProProcessAddForm.getFileUrl())
//                        .remark(resProProcessAddForm.getMoldRemark())
//                        .build();
//                resProductMoldDrawService.save(moldDraw);
//            }
//            //添加版本  把原来的设置为非默认
//            else {
//                one.setIsDefault("0");
//                one.setUpdateTime(LocalDateTime.now());
//                one.setModifier(JwtUtils.getLoginUserId());
//                one.setModifierName(JwtUtils.getLoginUsername());
//                resProductMoldDrawService.updateById(one);
//                //添加 一个新的版本
//                one.setId(null);
//                one.setFileUrl(resProProcessAddForm.getFileUrl());
//                one.setName(resProProcessAddForm.getMoldName());
//                one.setRemark(resProProcessAddForm.getMoldRemark());
//                one.setVersionName(UniqueIdGeneratorUtil.generateUniqueId("", "yyyyMMdd", 1000, 9999));
//                one.setIsDefault("1");
//                resProductMoldDrawService.save(one);
//            }
//        }
        //根据sku_code查询之前的数据查询之前的版本
        List<ProcessProjectData> list = resProEchnologyParamService.getOldVersionInfo(resProProcessAddForm.getTaskId());
        //如果无版本了信息 直接添加
        if (CollectionUtils.isEmpty(list)) {
            List<ProcessProjectData> projectTableData = resProProcessAddForm.getProjectTableData();
            //修改一次就多一条
            String code = UniqueIdGeneratorUtil.generateUniqueId("GXI", "yyyyMMdd", 1000, 9999);
            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 获取当前年份
            int currentYear = currentDate.getYear();
            ResProEchnologyParam build = ResProEchnologyParam.builder()
                    .creator(JwtUtils.getLoginUserId())
                    .creatorName(JwtUtils.getLoginUsername())
                    .createTime(LocalDateTime.now())
                    .updateTime(LocalDateTime.now())
                    .modifier(JwtUtils.getLoginUserId())
                    .modifierName(JwtUtils.getLoginUsername())
                    .templateId(resProProcessAddForm.getTemplateId())
                    .code(code)
                    .versionName("ves."+currentYear+"-"+1)
                    .taskId(resProProcessAddForm.getTaskId())
                    .isDefault(ProductEnum.dictEmum.S.getCode())
                    .build();
            //添加记录
            this.resProEchnologyParamService.save(build);
            for (ProcessProjectData info : projectTableData) {
                ResProEchnologyParamVersion buildVersion = ResProEchnologyParamVersion.builder()
                        .creator(JwtUtils.getLoginUserId())
                        .creatorName(JwtUtils.getLoginUsername())
                        .createTime(LocalDateTime.now())
                        .updateTime(LocalDateTime.now())
                        .modifier(JwtUtils.getLoginUserId())
                        .modifierName(JwtUtils.getLoginUsername())
                        .content(info.getContent())
                        .sorted(info.getSorted())
                        .name(info.getName())
                        .recordId(build.getId())
                        .code(info.getProCode())
                        .fixture(info.getFixture())
                        .measuringTools(info.getMeasuringTools())
                        .hoursQuota(info.getHoursQuota())
                        .unitId(info.getUnitId())
                        .ngSalaryQuota(info.getNgSalaryQuota())
                        .salaryQuota(info.getSalaryQuota())
                        .build();
                boolean save = resProEchnologyParamVersionService.save(buildVersion);
                if (save) {
                    List<ResProEchnologyParamVersionSku> versionSkuList = info.getVersionSkuList();
                    if (CollectionUtils.isNotEmpty(versionSkuList)) {
                        for (ResProEchnologyParamVersionSku res : versionSkuList) {
                            res.setEchnologyParamId(buildVersion.getId());
                            res.setCreateTime(LocalDateTime.now());
                            res.setCreator(JwtUtils.getLoginUserId());
                            res.setCreatorName(JwtUtils.getLoginUsername());
                        }
                        resProEchnologyParamVersionSkuService.saveBatch(versionSkuList);
                    }
                }
            }

        }
        // 如果有 先删在插入 再把删除的信息同步到version表
        else {
            //判断有没有变化咯
            Set<ProcessProjectData> dataOldSet = new HashSet<>(list);
            Set<ProcessProjectData> dataSet = new HashSet<>(resProProcessAddForm.getProjectTableData());
            //版本发生了变化
            if (!dataSet.equals(dataOldSet)) {
                //1.将原来的版本加入verson表中 生成新的版本号
                //修改一次就多一条
                //查询出当前的count
                LocalDate currentDate = LocalDate.now();
                // 获取当前年份
                int currentYear = currentDate.getYear();
                Integer count = this.resProEchnologyParamService.countVersion(resProProcessAddForm.getTaskId());
                String code = UniqueIdGeneratorUtil.generateUniqueId("GXI", "yyyyMMdd", 1000, 9999);
                //把所有的版本设置为非默认版本
                UpdateWrapper<ResProEchnologyParam> paramQueryWrapper = new UpdateWrapper<>();
                paramQueryWrapper.eq("task_id",resProProcessAddForm.getTaskId());
                paramQueryWrapper.set("is_default",ProductEnum.dictEmum.F.getCode());
                this.resProEchnologyParamService.update(paramQueryWrapper);
                //加入一个新的
                ResProEchnologyParam params = ResProEchnologyParam.builder()
                        .creator(JwtUtils.getLoginUserId())
                        .creatorName(JwtUtils.getLoginUsername())
                        .createTime(LocalDateTime.now())
                        .updateTime(LocalDateTime.now())
                        .modifier(JwtUtils.getLoginUserId())
                        .modifierName(JwtUtils.getLoginUsername())
                        .templateId(resProProcessAddForm.getTemplateId())
                        .code(code)
                        .versionName("ves."+currentYear+"-"+(count+1))
                        .taskId(resProProcessAddForm.getTaskId())
                        .isDefault(ProductEnum.dictEmum.S.getCode())
                        .build();
                //保存记录
                this.resProEchnologyParamService.save(params);
                List<ProcessProjectData> projectTableData = resProProcessAddForm.getProjectTableData();
                if (CollectionUtils.isNotEmpty(projectTableData)) {
                    projectTableData.forEach(info -> {
                        ResProEchnologyParamVersion buildVersion = ResProEchnologyParamVersion.builder()
                                .creator(info.getCreator())
                                .creatorName(info.getCreatorName())
                                .createTime(info.getCreateTime())
                                .updateTime(info.getUpdateTime())
                                .modifier(info.getModifier())
                                .modifierName(info.getModifierName())
                                .content(info.getContent())
                                .sorted(info.getSorted())
                                .name(info.getName())
                                .code(info.getProCode())
                                .recordId(params.getId())
                                .unitId(info.getUnitId())
                                .ngSalaryQuota(info.getNgSalaryQuota())
                                .fixture(info.getFixture())
                                .measuringTools(info.getMeasuringTools())
                                .hoursQuota(info.getHoursQuota())
                                .salaryQuota(info.getSalaryQuota())
                                .build();
                        boolean save = resProEchnologyParamVersionService.save(buildVersion);
                        if (save) {
                            List<ResProEchnologyParamVersionSku> versionSkuList = info.getVersionSkuList();
                            if (CollectionUtils.isNotEmpty(versionSkuList)) {
                                for (ResProEchnologyParamVersionSku res : versionSkuList) {
                                    res.setEchnologyParamId(buildVersion.getId());
                                    res.setCreateTime(LocalDateTime.now());
                                    res.setCreator(JwtUtils.getLoginUserId());
                                    res.setCreatorName(JwtUtils.getLoginUsername());
                                }
                                resProEchnologyParamVersionSkuService.saveBatch(versionSkuList);
                            }
                        }
                    });
                }
            }
        }
        return 1;
    }

    /**
     * 添加检测项
     *
     * @param resProQualityAddForm
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addSkuQuality(ResProQualityAddForm resProQualityAddForm) {
        //判断有没有产品信息
        List<TestItemData> projectInfoById = resProQualityProjectService.getProjectInfoById(resProQualityAddForm.getProductDetailId());
        if (CollectionUtils.isEmpty(projectInfoById)) {
            //如果没有过检测项
            List<TestItemData> testItemData = resProQualityAddForm.getTestItemData();
            List<ResProQualityProject> qualityProjects = new ArrayList<>();
            List<ResProQualityVersion> qualityVersions = new ArrayList<>();
            String versionName = UniqueIdGeneratorUtil.generateUniqueId("JCBB", "yyyyMMdd", 10, 99);
            testItemData.forEach(info -> {
                ResProQualityProject qualityProject = ResProQualityProject.builder()
                        .creator(JwtUtils.getLoginUserId())
                        .creatorName(JwtUtils.getLoginUsername())
                        .createTime(LocalDateTime.now())
                        .updateTime(LocalDateTime.now())
                        .modifier(JwtUtils.getLoginUserId())
                        .modifierName(JwtUtils.getLoginUsername())
                        .no(UniqueIdGeneratorUtil.generateUniqueId("JCX", "yyyyMMdd", 100, 999))
                        .name(info.getName())
                        .standard(info.getStandard())
                        .utensil(info.getUtensil())
                        .detectionRate(info.getDetectionRate())
                        .way(info.getWay())
                        .importance(info.getImportance())
                        .productDetailId(resProQualityAddForm.getProductDetailId())
                        .skuCode(resProQualityAddForm.getSkuCode())
                        .build();
                qualityProjects.add(qualityProject);

                ResProQualityVersion qualityVersion = ResProQualityVersion.builder()
                        .creator(JwtUtils.getLoginUserId())
                        .creatorName(JwtUtils.getLoginUsername())
                        .createTime(LocalDateTime.now())
                        .updateTime(LocalDateTime.now())
                        .modifier(JwtUtils.getLoginUserId())
                        .modifierName(JwtUtils.getLoginUsername())
                        .no(UniqueIdGeneratorUtil.generateUniqueId("JCX", "yyyyMMdd", 100, 999))
                        .name(info.getName())
                        .standard(info.getStandard())
                        .way(info.getWay())
                        .importance(info.getImportance())
                        .utensil(info.getUtensil())
                        .detectionRate(info.getDetectionRate())
                        .productDetailId(resProQualityAddForm.getProductDetailId())
                        .skuCode(resProQualityAddForm.getSkuCode())
                        .versionName(versionName)
                        .build();
                qualityVersions.add(qualityVersion);
            });
            resProQualityProjectService.saveBatch(qualityProjects);
            resProQualityVersionService.saveBatch(qualityVersions);
        } else {
            //判断有无更新
            Set<TestItemData> oldDataSet = new HashSet<TestItemData>(projectInfoById);
            Set<TestItemData> newDataSet = new HashSet<TestItemData>(resProQualityAddForm.getTestItemData());
            //有无更新操作
            if (!oldDataSet.equals(newDataSet)) {
                //加入历史
                String versionName = UniqueIdGeneratorUtil.generateUniqueId("JCBB", "yyyyMMdd", 10, 99);
                List<ResProQualityVersion> qualityVersions = new ArrayList<>();
                List<ResProQualityProject> qualityProjects = new ArrayList<>();
                projectInfoById.forEach(info -> {
                    ResProQualityVersion qualityVersion = ResProQualityVersion.builder()
                            .creator(info.getCreator())
                            .creatorName(info.getCreatorName())
                            .createTime(info.getCreateTime())
                            .updateTime(info.getUpdateTime())
                            .modifier(info.getModifier())
                            .modifierName(info.getModifierName())
                            .no(UniqueIdGeneratorUtil.generateUniqueId("JCX", "yyyyMMdd", 100, 999))
                            .name(info.getName())
                            .standard(info.getStandard())
                            .way(info.getWay())
                            .importance(info.getImportance())
                            .utensil(info.getUtensil())
                            .detectionRate(info.getDetectionRate())
                            .productDetailId(resProQualityAddForm.getProductDetailId())
                            .skuCode(resProQualityAddForm.getSkuCode())
                            .versionName(versionName)
                            .build();
                    qualityVersions.add(qualityVersion);
                });
                //加入历史版本
                resProQualityVersionService.saveBatch(qualityVersions);
                //删除原来数据
                LambdaQueryWrapper<ResProQualityProject> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(ResProQualityProject::getProductDetailId, resProQualityAddForm.getProductDetailId());
                resProQualityProjectService.remove(queryWrapper);
                //添加新的
                List<TestItemData> testItemData = resProQualityAddForm.getTestItemData();
                testItemData.forEach(info -> {
                    ResProQualityProject qualityProject = ResProQualityProject.builder()
                            .creator(JwtUtils.getLoginUserId())
                            .creatorName(JwtUtils.getLoginUsername())
                            .createTime(LocalDateTime.now())
                            .updateTime(LocalDateTime.now())
                            .modifier(JwtUtils.getLoginUserId())
                            .modifierName(JwtUtils.getLoginUsername())
                            .no(UniqueIdGeneratorUtil.generateUniqueId("JCX", "yyyyMMdd", 100, 999))
                            .name(info.getName())
                            .standard(info.getStandard())
                            .way(info.getWay())
                            .importance(info.getImportance())
                            .utensil(info.getUtensil())
                            .detectionRate(info.getDetectionRate())
                            .productDetailId(resProQualityAddForm.getProductDetailId())
                            .skuCode(resProQualityAddForm.getSkuCode())
                            .build();
                    qualityProjects.add(qualityProject);
                });
                resProQualityProjectService.saveBatch(qualityProjects);
            }
        }
        return 1;
    }

    /**
     * 提交校对
     *
     * @param id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int submitProofread(String id) {
        ResProTask byId = resProTaskService.getById(id);
        byId.setStatus(MaintenanceEnum.Task_Status_Enum.DDX.getCode());
        byId.setUpdateTime(LocalDateTime.now());
        byId.setModifier(JwtUtils.getLoginUserId());
        byId.setModifierName(JwtUtils.getLoginUsername());
        this.updateById(byId);

        //查询物料id
        ProductDetail detail = productDetailService.getById(byId.getSkuId());

        if (ObjectUtil.isNotEmpty(detail)) {
            QueryWrapper<BenchmarkBook> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("res_task_id", byId.getId());
            BenchmarkBook one = benchmarkBookService.getOne(queryWrapper);
            if (ObjectUtil.isEmpty(one)) {
                //插入基准书
                BenchmarkBook benchmarkBook = BenchmarkBook.builder()
                        .createTime(LocalDateTime.now())
                        .resTaskId(byId.getId())
                        .code(UniqueIdGeneratorUtil.generateUniqueId(detail.getSkuCode(), null, 100, 200))
                        .bookType(MaintenanceEnum.BenchmarkBookType.DYJZS.getCode())
                        .skuName(detail.getSkuName())
                        .skuCode(detail.getSkuCode())
                        .skuSpec(detail.getSkuSpec())
                        .source(byId.getSource())
                        .productType(detail.getProductTypeId())
                        .materialNature(detail.getProductNature())
                        .productAttr(detail.getAssemblyNature())
                        .status(MaintenanceEnum.BenchmarkBookStatus.DZS.getCode())
                        .makePerson(JwtUtils.getLoginUserId())
                        .build();
                benchmarkBookService.save(benchmarkBook);
            }
        }
        return 1;
    }


    /**
     * 确认信息并校对
     *
     * @param id
     * @param proofreadResult
     * @param remark
     * @return
     */
    @Override
    @Transactional
    public int submitProofreadTo(String id, String proofreadResult, String remark) {
        ResProTask byId = resProTaskService.getById(id);
        //审核通过
        if (MaintenanceEnum.TASK_PROOFREAD_ENUM.GDTG.getCode().equals(proofreadResult)) {
            byId.setStatus(MaintenanceEnum.Task_Status_Enum.DDX.getCode());
            //审核通过 改变状态
            QueryWrapper<BenchmarkBook> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("res_task_id", byId.getId());
            BenchmarkBook one = benchmarkBookService.getOne(queryWrapper);
            if (ObjectUtil.isNotEmpty(one)) {
                one.setStatus(MaintenanceEnum.BenchmarkBookStatus.DZS.getCode());
                one.setAdjustPerson(JwtUtils.getLoginUserId());
                one.setAuditTime(LocalDateTime.now());
                boolean b = benchmarkBookService.updateById(one);
                if (b) {
                    byId.setProofreadName(JwtUtils.getLoginUsername());
                    byId.setProofreadTime(LocalDateTime.now());
                    resProTaskService.updateById(byId);
                }
            }
        } else if (MaintenanceEnum.TASK_PROOFREAD_ENUM.BHTZ.getCode().equals(proofreadResult)) {
            byId.setStatus(MaintenanceEnum.Task_Status_Enum.DGH.getCode());
            byId.setProofreadName(JwtUtils.getLoginUsername());
            byId.setProofreadTime(LocalDateTime.now());
            resProTaskService.updateById(byId);
        }
        return 1;
    }

    /**
     * 确认并审核
     *
     * @param id
     * @param auditResult
     * @param remark
     * @return
     */
    @Override
    @Transactional
    public int submitAudit(String id, String auditResult, String remark) {
        ResProTask byId = resProTaskService.getById(id);
        //审核通过
        if (MaintenanceEnum.TASK_PROOFREAD_ENUM.GDTG.getCode().equals(auditResult)) {
            byId.setStatus(MaintenanceEnum.Task_Status_Enum.YDX.getCode());
            //审核通过 改变状态
            QueryWrapper<BenchmarkBook> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("res_task_id", byId.id);
            BenchmarkBook one = benchmarkBookService.getOne(queryWrapper);
            if (ObjectUtil.isNotEmpty(one)) {
                one.setStatus(MaintenanceEnum.BenchmarkBookStatus.YDX.getCode());
                one.setAdjustPerson(JwtUtils.getLoginUserId());
                one.setAuditTime(LocalDateTime.now());
                one.setBookType(MaintenanceEnum.BenchmarkBookType.ZSJZS.getCode());
                boolean b = benchmarkBookService.updateById(one);
                if (b) {
                    byId.setAuditName(JwtUtils.getLoginUsername());
                    byId.setAuditTime(LocalDateTime.now());
                    resProTaskService.updateById(byId);
                }
            }
        } else if (MaintenanceEnum.TASK_PROOFREAD_ENUM.BHTZ.getCode().equals(auditResult)) {
            byId.setStatus(MaintenanceEnum.Task_Status_Enum.DGH.getCode());
            byId.setAuditName(JwtUtils.getLoginUsername());
            byId.setAuditTime(LocalDateTime.now());
            resProTaskService.updateById(byId);
        }
        return 1;

    }

    /**
     * 修改研发任务
     * @param form
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateInfo(ResProTaskAddForm form) {
        //公共部分
        //1.更新 任务表的数据
        ResProTask resProTask = this.getById(form.getId());
        BeanUtils.copyProperties(form, resProTask);
        this.updateById(resProTask);
        //2. 修改内部产品信息
        ProductDetail byId = productDetailService.getById(resProTask.getSkuId());
        byId.setModifier(JwtUtils.getLoginUserId());
        byId.setModifierName(JwtUtils.getLoginUsername());
        byId.setUpdateTime(LocalDateTime.now());
        byId.setRemark(form.getInRemark());
        byId.setSellStatus("0");
        byId.setSkuCode(form.getInSkuCode());
        byId.setSkuName(form.getInSkuName());
        byId.setSkuSpec(form.getInSkuSpec());
        byId.setProductTypeId(form.getProductTypeId());
        byId.setProductNature(form.getProductNature());
        byId.setAssemblyNature(form.getAssemblyNature());
        byId.setBaseUnit(form.getInUnitId());
        byId.setMainCalWay(form.getMainCalWay());
        //主计量方式
        byId.setMainUnitId(form.getMainUnitId());
        //主计量单位
        byId.setMainUnitRate(form.getMainUnitRate());
        //主计量单位换算率
        byId.setSubCalWay(form.getSubCalWay());
        //辅计量方式
        byId.setSubUnitId(form.getSubUnitId());
        //辅计量单位
        byId.setSubUnitRate(form.getSubUnitRate());
        //辅计量单位换算率
        byId.setCostCheckType(form.getCostCheckType());
        //成本核算类型
        byId.setCheckStatus(form.getCheckStatus());
        //是否质检
        byId.setBoxStatus(form.getBoxStatus());
        //修改
        productDetailService.updateById(byId);
        //判断是否客户订单
        if (form.getSource().equals(MaintenanceEnum.Task_Source_Enum.KHDD.getCode())) {
            //客户订单 想要修改客户产品
            //判断是否重新上传了图纸
            if ( StrUtil.isNotEmpty(form.getFileName()) && StrUtil.isNotEmpty(form.getAttachmentPdf())) {
                //修改其他的图纸为非默认
                UpdateWrapper<ResProductDraw> drawQueryWrapper = new UpdateWrapper<>();
                drawQueryWrapper.eq("task_id", resProTask.getId());
                drawQueryWrapper.eq("product_detail_id", resProTask.getSkuId());
                drawQueryWrapper.set("is_default",ProductEnum.dictEmum.F.getCode());
                boolean update = this.resProductDrawService.update(drawQueryWrapper);
                if (update) {
                    LocalDate currentDate = LocalDate.now();
                    // 获取当前年份
                    int currentYear = currentDate.getYear();

                    Integer count = resProductDrawService.getCountForDraw(resProTask.getId(),resProTask.getSkuId());

                    ResProductDraw draw = ResProductDraw.builder().creator(JwtUtils.getLoginUserId()).creatorName(JwtUtils.getLoginUsername())
                            .createTime(LocalDateTime.now()).updateTime(LocalDateTime.now()).modifier(JwtUtils.getLoginUserId())
                            .modifierName(JwtUtils.getLoginUsername()).versionName(UniqueIdGeneratorUtil.generateUniqueId("", "yyyyMMdd", 1000, 9999))
//                            .fileUrl(form.getAttachmentPdf())
//                            .name(form.getFileName()).code(UniqueIdGeneratorUtil.generateUniqueId("TZ", "yyyyMMdd", 1000, 9999))
                            .isDefault(ProductEnum.dictEmum.S.getCode())
                            .productDetailId(resProTask.getSkuId())
                            .versionName("ves."+currentYear+"-"+count+1)

                            .remark(form.getProcessDescription())
                            .isRelevance(ProductEnum.dictEmum.F.getCode())
                            .taskId(resProTask.getId())
                            .build();
                    resProductDrawService.save(draw);
                }

                QueryWrapper<OrderProEnclosure> enclosureQueryWrapper = new QueryWrapper<>();
                enclosureQueryWrapper.eq("task_id", resProTask.getId());
                OrderProEnclosure one = this.orderProEnclosureService.getOne(enclosureQueryWrapper);
                if (ObjectUtil.isNotEmpty(one)) {
                    one.setUpdateTime(LocalDateTime.now());
                    one.setModifier(JwtUtils.getLoginUserId());
                    one.setModifierName(JwtUtils.getLoginUsername());
                    one.setFileName(form.getFileName());
                    one.setFileUrl(form.getAttachmentPdf());
                    orderProEnclosureService.updateById(one);
                }
            }


        }
        else {
            //判断图片是否上传
            if ( StrUtil.isNotEmpty(form.getFileName()) && StrUtil.isNotEmpty(form.getAttachmentPdf())) {
                //修改其他的图纸为非默认
                UpdateWrapper<ResProductDraw> drawQueryWrapper = new UpdateWrapper<>();
                drawQueryWrapper.eq("task_id", resProTask.getId());
                drawQueryWrapper.eq("product_detail_id", resProTask.getSkuId());
                drawQueryWrapper.set("is_default",ProductEnum.dictEmum.F.getCode());
                boolean update = this.resProductDrawService.update(drawQueryWrapper);
                if (update) {
                    Integer count = resProductDrawService.getCountForDraw(resProTask.getId(),resProTask.getSkuId());
                    // 获取当前日期
                    LocalDate currentDate = LocalDate.now();
                    // 获取当前年份
                    int currentYear = currentDate.getYear();

                    //查询当前有多少个版本
                    ResProductDraw draw = ResProductDraw.builder().creator(JwtUtils.getLoginUserId()).creatorName(JwtUtils.getLoginUsername())
                            .createTime(LocalDateTime.now()).updateTime(LocalDateTime.now()).modifier(JwtUtils.getLoginUserId())
                            .modifierName(JwtUtils.getLoginUsername()).versionName(UniqueIdGeneratorUtil.generateUniqueId("", "yyyyMMdd", 1000, 9999))
                            .isDefault(ProductEnum.dictEmum.S.getCode())
                            .productDetailId(resProTask.getSkuId())
                            .remark(form.getProcessDescription())
                            .versionName("ves."+currentYear+"-"+count+1)
                            .isRelevance(ProductEnum.dictEmum.F.getCode())
                            .taskId(resProTask.getId())
                            .build();
                    resProductDrawService.save(draw);
                }

                QueryWrapper<OrderProEnclosure> enclosureQueryWrapper = new QueryWrapper<>();
                enclosureQueryWrapper.eq("task_id", resProTask.getId());
                OrderProEnclosure one = this.orderProEnclosureService.getOne(enclosureQueryWrapper);
                if (ObjectUtil.isNotEmpty(one)) {
                    one.setUpdateTime(LocalDateTime.now());
                    one.setModifier(JwtUtils.getLoginUserId());
                    one.setModifierName(JwtUtils.getLoginUsername());
                    one.setFileName(form.getFileName());
                    one.setFileUrl(form.getAttachmentPdf());
                    orderProEnclosureService.updateById(one);
                }
            }
        }
        //添加检测项
        ResProQualityAddForm resProProcessAddForm = new ResProQualityAddForm();
        resProProcessAddForm.setSkuCode(form.getInSkuCode());
        resProProcessAddForm.setProductDetailId(resProTask.getSkuId());
        resProProcessAddForm.setTestItemData(form.getTestItemData());
        this.addSkuQuality(resProProcessAddForm);

        return 1;
    }


    /**
     * 提交校对
     * @param id
     * @return
     */
    @Override
    public int confirm(String id) {

        //            String newProductCode = UniqueIdGeneratorUtil.generateUniqueId("CP", "yyyyMMdd", 1000, 9999);
//            //插入客户产品目录表
//            QueryWrapper<CustomerProductCatalog>  caWrapper = new QueryWrapper<>();
//            caWrapper.eq("ext_product_id", form.getExtProductId());
//            caWrapper.eq("customer_id", form.getCustomerId());
//            CustomerProductCatalog catalog = catalogService.getOne(caWrapper);
//            catalog.setModifier(JwtUtils.getLoginUserId());
//            catalog.setModifierName(JwtUtils.getLoginUsername());
//            catalog.setUpdateTime(LocalDateTime.now());
//            catalog.setCustomerId(form.getCustomerId());
//            catalog.setSkuCode(form.getCusSkuCode());
//            catalog.setCusProductType(form.getCusProductCategory());
//            catalog.setCusProductSpec(form.getCusProductSpec());
//            catalog.setCusProductName(form.getCusProductName());
//            catalog.setPlanGivenTime(form.getPlanGivenTime());
//            catalog.setCusProductCode(newProductCode);
//            catalog.setCusProductUnit(form.getCusProUnitId());
//            catalog.setInSkuCode(productId);
//            catalog.setAssignNew(form.getIsUseOrAdd());
//            catalog.setQuantity(form.getCusProductCount());
//            //包装说明
//            catalog.setRemark(form.getRemark());
//            catalogService.updateById(catalog);

        //查询
        ResProTask byId = resProTaskService.getById(id);
        if (ObjectUtil.isNotEmpty(byId)) {

            if (byId.getSource().equals(MaintenanceEnum.Task_Source_Enum.KHDD.getCode())) {
                QueryWrapper<CustomerProductCatalog>  caWrapper = new QueryWrapper<>();
                caWrapper.eq("ext_product_id", byId.getExtProductId());
                caWrapper.eq("customer_id", byId.getCustomerId());
                CustomerProductCatalog catalog = catalogService.getOne(caWrapper);
                catalog.setModifier(JwtUtils.getLoginUserId());
                catalog.setModifierName(JwtUtils.getLoginUsername());
                catalog.setUpdateTime(LocalDateTime.now());
                catalog.setInSkuCode(byId.getSkuId());
                //修改绑定的信息
                boolean b = catalogService.updateById(catalog);
                if (b){
                    byId.setStatus(MaintenanceEnum.Task_Status_Enum.DGH.getCode());
                    byId.setUpdateTime(LocalDateTime.now());
                    byId.setModifier(JwtUtils.getLoginUserId());
                    byId.setModifierName(JwtUtils.getLoginUsername());
                    boolean updateById = this.updateById(byId);
                    if (updateById) {
                        return 1;
                    }
                }
            }else{
                byId.setStatus(MaintenanceEnum.Task_Status_Enum.DGH.getCode());
                byId.setUpdateTime(LocalDateTime.now());
                byId.setModifier(JwtUtils.getLoginUserId());
                byId.setModifierName(JwtUtils.getLoginUsername());
                boolean updateById = this.updateById(byId);
                if (updateById) {
                    return 1;
                }
            }
        }
        return 0;
    }
}
